#include "drv_sg90.h"
void drv_sg90_init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
	TIM_OCInitTypeDef TIM_OCInitStruct;

	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);//开GPIOF时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14, ENABLE);//开TIM13时钟
	
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;//复用模式
	GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;//推挽
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_7;
	GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;//使能上拉
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;//速率
	GPIO_Init(GPIOA, &GPIO_InitStruct);

	GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_TIM14);//把PF8复用为TIM13

	TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;//不分频
	TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;//向上计数
	TIM_TimeBaseInitStruct.TIM_Period = 20000-1;//自动重装载值
	TIM_TimeBaseInitStruct.TIM_Prescaler = 84-1;//预分频
	TIM_TimeBaseInit(TIM14, &TIM_TimeBaseInitStruct);
	TIM_ITConfig(TIM14, TIM_IT_Update, ENABLE);//定时器的更新中断

	TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;//定时器输出模式为PWM1
	TIM_OCInitStruct.TIM_OCPolarity= TIM_OCPolarity_High;//输出比较通道的有效极性为低电平
	TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;//使能定时器输出比较通道的输出
	TIM_OCInitStruct.TIM_Pulse = 0;//PWM的比较值
	TIM_OC1Init(TIM14, &TIM_OCInitStruct);

	TIM_ARRPreloadConfig(TIM14, ENABLE);//使能TIM13的自动重装值预装载
	TIM_OC1PreloadConfig(TIM14, TIM_OCPreload_Enable);//TIM13通道1的输出比较预装载
	//TIM_CtrlPWMOutputs(TIM13, ENABLE);

	TIM_Cmd(TIM14, ENABLE);
}
void SG90_SetAngle(uint16_t angle)
{
	uint16_t pulse_us;
	pulse_us = 500+500*(angle/45);
	TIM_SetCompare1(TIM14,pulse_us);
}

